<?php

class AccountsController extends Controller
{
	/**
	 * @return array action filters
	 */
	public function filters() {
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules() {
		return array(
			array('allow', // allow all users to perform below actions
				'actions'=>array('register', 'login', 'passwordFind', 'passwordReset'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform below actions
				'actions'=>array('logout', 'index'),
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				'actions'=>array('logout', 'index'),
				'users'=>array('*'),
			),
		);
	}
	
	public function actionIndex()
	{
		//TODO: go to merchant page
		$url = Yii::app()->createUrl('/merchant');
		Yii::app()->request->redirect($url, true);
		//$this->render('index');
	}
	
	public function actionRegister()
	{
		// save to register
		$model = new MerchantForm('register');
		
		// if it is ajax validation request
		if (isset($_POST['ajax']) && $_POST['ajax'] === 'register-form') {
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		// collect user input data
		if (isset($_POST['MerchantForm'])) {
			$model->attributes = $_POST['MerchantForm'];
			// validate user input and redirect to the previous page if valid
			if ($model->checkEmail() && $model->save()) {				
				//TODO: send admin email
				$subject = 'Register Merchant Account ' . date('Y-m-d H:i:s');
				$body = '<pre>' . print_r($_POST['MerchantForm'], 1) . '</pre>';
				BUtils::EmailAdmin($subject, $body);
				
				Yii::app()->user->setFlash('register',
					BUtils::T('biz_account_registered_msg') . '<br /><br />');
				$this->refresh();
			} else {
				//send admin email
				$subject = 'ERROR Merchant Account: ' . date('Y-m-d H:i:s');
				$body = '<pre>' . print_r($_POST['MerchantForm'], 1) . '</pre>';
				$body .= print_r($model->getErrors(), 1);
				BUtils::EmailAdmin($subject, $body);
			}
		}
		
		// display the signup form
		$this->render('register', array('model'=>$model));
	}

	public function actionLogin()
	{
		$model = new LoginForm('login');

		// if it is ajax validation request
		if (isset($_POST['ajax']) && $_POST['ajax']==='login-form') {
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		// collect user input data
		if (isset($_POST['LoginForm'])) {
			$model->attributes = $_POST['LoginForm'];
			// validate user input and redirect to the previous page if valid
			if ($model->validate() && $model->login()) {
				BUtils::LoggingAction(Yii::app()->user->id, 0);
				
				//go to original url
				$this->redirect(Yii::app()->user->returnUrl, true);
			}
		}
		
		// display the login form
		$this->render('login', array('model'=>$model));
	}

	public function actionLogout()
	{
		BUtils::LoggingAction(Yii::app()->user->id, 1);
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}
	
	public function actionPasswordFind() {
		$model = new LoginForm('passwordFind');
		
		// collect user input data
		if (isset($_POST['LoginForm'])) {
			$model->attributes = $_POST['LoginForm'];
			// check this email is valid
			$sql_email = 'SELECT email FROM tbl_merchant_account WHERE email=:email';
			$connection = Yii::app()->db;
			$command = $connection->createCommand($sql_email);
			$row = $command->queryRow(true, array(':email' => $model->email));
			if (empty($row)) {
				$connection->active = false;
				Yii::app()->user->setFlash('error', 
					BUtils::T('password_find_email_not_exist_msg', array('{email}'=>$model->email, '{sys_email}'=>'business@yamii.fi')));
				$this->refresh();
			}
			
			//send a reset passwork link and insert a record into table tbl_password_request_session
			//1. create token session
			$session_token = uniqid() . rand(100, 999);
			$sql_password_reset = 'INSERT INTO tbl_token_password_reset (token, email) VALUES (:token, :email)';
			$command = $connection->createCommand($sql_password_reset);
			$command->execute(array(
				':token' => $session_token,
				':email' => $row['email'],
			));
			$connection->active = false;
			
			//2.send email
			$this->_emailPasswordFind($session_token, $row['email']);
			
			$login_button = CHtml::link(BUtils::T('login_lbl'), Yii::app()->createUrl('/accounts/login'));
			Yii::app()->user->setFlash('done', BUtils::T('password_find_email_sent_msg') . $login_button);
		}
		
		$this->render('passwordFind', array('model'=>$model));
	}
	
	public function actionPasswordReset() {
		$e = Yii::app()->request->getQuery('e');
		if (empty($e)) {
			throw new CHttpException(404, 'The requested page does not exist.');
		}
		
		//check if this e=? exists on table
		$sql_token = 'SELECT token, UNIX_TIMESTAMP(insert_time) AS ts_insert, email FROM tbl_token_password_reset WHERE token=:token ';
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_token);
		$row = $command->queryRow(true, array(':token' => $e));
		$connection->active = false;
		$expired = false;
		if (empty($row['token'])) {
			$expired = true;
		} else {
			$diff_sec = time() - $row['ts_insert'];
			if ($diff_sec > 24*3600*3) { // 3 days expired
				$expired = true;
			}
		}
		if ($expired) {
			$url = Yii::app()->createUrl('/accounts/passwordResetExpired');
			Yii::app()->request->redirect($url);
		}
		
		$model = new LoginForm('register');
		$model->email = $row['email'];
		
		// collect user input data
		if (isset($_POST['LoginForm'])) {
			$new_password = $_POST['LoginForm']['password'];
			$repeat_password = $_POST['LoginForm']['password_repeat'];
			if ($new_password != $repeat_password) {
				Yii::app()->user->setFlash('password_repeat', 'The repeat password is different than your new password! Please repeat your new password again!');
				$this->refresh();
			} else {
				if ($model->resetPassword($new_password)) {
					//set the history
					$sql_token = 'UPDATE tbl_token_password_reset
						SET action_status=1, action_time=NOW(), ip=:ip, agent=:agent
						WHERE token=:token ';
					$connection = Yii::app()->db;
					$command = $connection->createCommand($sql_token);
					$command->execute(array(
						':token' => $e,
						':ip' => Yii::app()->request->getUserHostAddress(),
						':agent' => Yii::app()->request->getUserAgent(),
					));
					$connection->active = false;
					
					//send password changed email
					$this->_emailPasswordChanged($row['token'], $row['email']);
					
					//send admin email as well
					$subject = 'Merchant Changed Password ' . date('Y-m-d H:i:s');
					$body = '<pre>' . print_r($_POST['LoginForm'], 1) . print_r($row, 1) . '</pre>';
					BUtils::EmailAdmin($subject, $body);
					
					$login_button = CHtml::link(BUtils::T('login_lbl'), Yii::app()->createUrl('/accounts/login'));
					Yii::app()->user->setFlash('done', BUtils::T('password_reset_done_msg') . $login_button);
					$this->refresh();
				} else {
					Yii::app()->user->setFlash('error', 'The password is not changed! ');
					$this->refresh();
				}
			}
		}
		
		$this->render('passwordReset', array('model'=>$model));
	}
	
	public function actionPasswordResetExpired() {
		$this->render('passwordResetExpired');
	}
	
	/**
	 * Push client message
	 */
	public function actionPush() {
		BUtils::Logging('push', $_REQUEST);
	}
	
	private function _emailPasswordFind($session_token, $email) {
		//2. send link to user's email
		$reset_password_link = Yii::app()->createAbsoluteUrl('/accounts/passwordReset', array('e'=>$session_token));
		$email_text_tpl = <<<TEXT
Hello,

You've just asked for the password of your Yamii for Business account. For security reasons, Yamii doesn't send passwords by e-mail, but you can change your password by the following link with your bowser.

Change your password:
{$reset_password_link}

Best regards,
The Yamii Team
LBB Solutions Oy
http://business.yamii.fi
TEXT;
			$email_html_tpl = <<<HTML
Hello,<br/>
<br/>
You've just asked for the password of your Yamii for Business account. For security reasons, Yamii doesn't send passwords by e-mail, but you can change your password by the following link with your bowser.<br/>
<br/>
<a href="{$reset_password_link}" target="_blank">Change your password</a><br/>
<br/>
Best regards,<br/>
The Yamii Team<br/>
LBB Solutions Oy<br/>
http://business.yamii.fi
HTML;
			BUtils::SendEmailOut('Change your password?', $email, $email_html_tpl, $email_text_tpl);
	}
	
	private function _emailPasswordChanged($session_token, $email) {
		//2. send link to user's email
		$reset_password_link = Yii::app()->createAbsoluteUrl('/accounts/passwordReset', array('e'=>$session_token));
		$email_text_tpl = <<<TEXT
Hello,

Your Yamii password was changed. Please contact us if you have any question.

Best regards,
The Yamii Team
LBB Solutions Oy
http://business.yamii.fi
TEXT;
			$email_html_tpl = <<<HTML
Hello,<br/>
<br/>
Your Yamii password was changed. Please contact us if you have any question.<br/>
<br/>
Best regards,<br/>
The Yamii Team<br/>
LBB Solutions Oy<br/>
http://business.yamii.fi
</p>
HTML;
			BUtils::SendEmailOut('Your password was changed.', $email, $email_html_tpl, $email_text_tpl);
	}
}